package com.yonyou.ucf.mdf.app.extend.event;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.yonyou.cloud.common.AbstractCommonConfigKey;
import com.yonyou.cloud.middleware.MiddlewareRuntimeEnvironment;
import com.yonyou.diwork.ott.exexutors.RobotExecutors;
import com.yonyou.iuap.event.model.BusinessEvent;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dao.app.BillContextDao;
import com.yonyou.ucf.mdd.ext.model.BillContext;
import com.yonyou.ucf.mdd.ext.poi.constant.POIConstant;
import com.yonyou.ucf.mdd.ext.poi.importbiz.service.ImportDataEventService;
import com.yonyou.ucf.mdd.ext.util.GsonExtUtils;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.module.isv.event.ISVEventListener;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.network.cryptor.EncryptionHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: zhuyjh
 * @Date: 2022/10/18 16:06
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ISVEventBatchImportEvent implements ISVEventListener<ISVDemoEventClass> {

    @Override
    public boolean onEvent(String type, ISVDemoEventClass event, EncryptionHolder holder) {
        //已经解密过了
        String content = event.getContent();
        if (StringUtils.isNotBlank(content)){
            log.info(">>>#onEvent#ISVEventBatchImportEvent:{}", content);
            if (content != null && content.length() != 0) {
                BusinessEvent businessEvent = (BusinessEvent) JSONObject.parseObject(content, BusinessEvent.class);
                businessEvent.setUserObject(content);
                Map<String,Object> reveiveData = GsonExtUtils.getMap(content);
                HashMap importDataEvent = (HashMap) reveiveData.get("importDataEvent");
                HashMap importContextDto = (HashMap) importDataEvent.get("importContextDto");
                String billno = importContextDto.get("billno").toString();
                String tenantId = importContextDto.get("tenantId").toString();
                BillContextDao billContextDao = (BillContextDao) AppContext.getBean("billContextDao");
                BillContext mddContext = null;
                String domain = null;

                mddContext = RobotExecutors.runAs(tenantId,()->{
                    BillContext mddContextTmp = null;
                    try {
                        mddContextTmp = billContextDao.findByBillnum(billno);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return mddContextTmp;
                });

                if(mddContext != null) {
                    domain = mddContext.getDomain();
                }
                if (domain != null) {
                    String appCode = (String) MiddlewareRuntimeEnvironment.get(AbstractCommonConfigKey.APP_CODE);
                    if (!domain.equals(appCode)) {
                        return true;
                    }
                }
                batchImport(businessEvent,tenantId);
            }
            return true;
        }
        return false;
    }
    public static String batchImport(BusinessEvent businessEvent,String tenantId) {
        if (businessEvent == null) {
            log.info(">>>#EventBatchImport#参数信息为空，不需要进行导入！");
            return null;
        }
        ImportDataEventService importDataEventService = AppContext.getApplicationContext().
                getBean(ImportDataEventService.class);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put(ImportDataEventService.RESULT_FLAG, POIConstant.SUCCESS);
        try {
            log.info("handle event－－－－－－》");
            String objectrep = RobotExecutors.runAs(tenantId,()->{
                return importDataEventService.importHandleReceiveEvent(businessEvent);
            });
            return objectrep;

        } catch (Exception e) {
            log.error("event handle exception",e);
            resultMap.put(ImportDataEventService.RESULT_FLAG,POIConstant.FAIL);
        }
        return GsonExtUtils.getJson(resultMap);
    }

    @Override
    public int priority() {
        return ISVEventListener.super.priority()-145;
    }

    @Override
    public Set<String> supportTypes() {
        return Sets.newHashSet(ISVDemoEventExtendType.EVENT_BATCH_IMPORT);
    }

    @Override
    public Class<ISVDemoEventClass> getEventClass() {
        return ISVDemoEventClass.class;
    }
}
